package com.ming.luckyDemo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ming.luckyDemo.pojo.DO.UserInfoDO;
import com.ming.luckyDemo.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class JWTTest {
    @Autowired
    //省略

    @GetMapping("/user/login")
    public Map<String,Object> login(UserInfoDO userInfoDO) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            //登录Service
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id","数据库的id");
            payload.put("name","数据库的name");
            //生成JWT令牌
            String token = JWTUtil.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            //响应token
            map.put("token",token);
        } catch (Exception e) {
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String,Object> test(HttpServletRequest request,String x) {
        HashMap<String, Object> map = new HashMap<>();
        //token=xx.xx.xx的头信息
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtil.verify(token);
        //通过k-v中的键取出（k不可以重复）
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        System.out.println(id);
        System.out.println(name);
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }
}
